package sync;

public class WindowsTest {
    public static void main(String[] args) {

        Window2 w1 = new Window2();

        Thread t1 = new Thread(w1,"线程一 ");
        Thread t2 = new Thread(w1,"线程二 ");
        Thread t3 = new Thread(w1,"线程三 ");

        t1.start();
        t2.start();
        t3.start();

//        Thread3 t3 = new Thread3();
//        Thread3 t4 = new Thread3();
//        Thread3 t5 = new Thread3();
//
//        t3.start();
//        t4.start();
//        t5.start();

    }
}
class Window implements Runnable{

    private int ticket = 100;
    Object obj = new Object();
    @Override
    public void run() {
        while (true) {
//            synchronized (obj){
            synchronized (this){//这个锁对象可以用this自身,就是当前调用run方法的window对象
                if (ticket>0){
                    System.out.println(Thread.currentThread().getName() + "卖票:" + ticket);
                    ticket--;
                }else {
                    break;
                };
            }
        }
    }
}

/*
 * 同步的方式二:使用同步方法:方法名使用synchronized修饰
 * */
class Window2 implements Runnable{

    private int ticket = 100;
    Object obj = new Object();
    @Override
    public void run() {
        while (true) {
            buyTicket();
        }
    }
    private synchronized void buyTicket(){
        if (ticket>0){
            System.out.println(Thread.currentThread().getName() + "卖票:" + ticket);
            ticket--;
        }
    }
}

/*
* 继承Thread方式的多线程同步方法
* 使用synchronized修饰的方法来执行要操作共享数据的代码
* 同步方法中依然需要同步锁,只是不需要显示指定,默认是当前类
* */
class Thread3 extends Thread{

    private static int ticket = 100;
    @Override
    public void run() {
        while (true) {
            buyTicket();
        }
    }
    private static synchronized void buyTicket(){
        if (ticket>0){
            System.out.println(Thread.currentThread().getName() + "卖票:" + ticket);
            ticket--;
        }
    }
}
